package com.wanchuang.qhbb.utils.updateutil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import kale.ui.view.dialog.EasyDialog;

public class UpdateManager {

    private String downLoadPath = ""; // 保存路径
    private String url = "";//apk下载地址
    private String newApkName  = ""; // apk名字
    private ProgressDialog dialog = null; // 进度弹框

    private boolean isforce = false;
    private Context context;
    private String content = "";

    private FragmentManager fm;
    public static UpdateManager updateManager;


    public static UpdateManager getInstance() {
        if (updateManager == null) {
            updateManager = new UpdateManager();
        }
        return updateManager;
    }

    public void start(){
        showUpdateDialog();
    }



    /**
     * 更新提示框
     */
    private void  showUpdateDialog() {
        UpDateDialog.Builder builder = new UpDateDialog.Builder(context);
        builder.setListener(new UpDateDialog.OnUpdateClickListener() {
            @Override
            public void onClick(View v) {
                // 下载进度框
                showProDialog();
                // 开始下载
                startDownLoad();
            }
        }).setForce(isforce).setContent(content);
        EasyDialog build = builder.build();
        build.setCancelable(!isforce);
        build.show(fm);
    }
    /**
     * 进度弹窗
     */
    private void showProDialog() {
        dialog = new ProgressDialog(context);
        dialog.setMessage("正在下载...");
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMax(100);
        dialog.setProgress(0);
        dialog.setCancelable(false);
        dialog.show();
    }

    /**
     * 获取下载路径
     */
    public String getDiskCacheDir(Context context) {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }

    /**
     * 开始下载
     */
    private void startDownLoad() {
        // 获取下载路径
        downLoadPath =  getDiskCacheDir(context);
        Log.e("DOWNLOAD", "downLoadPath: "+downLoadPath);
        new Thread(new Runnable() {
            @Override
            public void run() {
                downloadApk();
            }
        }).start();
    }


    /**
     * 下载APK
     */
    private void downloadApk() {
        try {
            final long startTime = System.currentTimeMillis();
            Log.i("DOWNLOAD", "startTime=" + startTime);
            newApkName = startTime + ".apk";
            //获取文件名
            URL myURL = new URL(url);
            URLConnection conn = myURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            int fileSize = conn.getContentLength();//根据响应获取文件大小
            Log.i("DOWNLOAD", "总大小=" + fileSize);
            if (fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
            if (is == null) throw new RuntimeException("服务器异常");
            File file1 = new File(downLoadPath);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            //把数据存入路径+文件名
            FileOutputStream fos = new FileOutputStream(downLoadPath + "/" + newApkName);
            byte buf[] = new byte[1024];
            int downLoadFileSize = 0;
            do {
                //循环读取
                int numread = is.read(buf);
                if (numread == -1) {
                    break;
                }
                fos.write(buf, 0, numread);
                downLoadFileSize += numread;
                Log.i("DOWNLOAD", "downLoadFileSize=" + downLoadFileSize);
                Log.i("DOWNLOAD", "fileSize=" + fileSize);
                Log.i("DOWNLOAD", "download downLoadFileSize=" + (int) ((float) downLoadFileSize * 100 / fileSize));
                //更新进度条
                dialog.setProgress((int)((float)downLoadFileSize*100/fileSize));
            } while (true);
//            delOldApk(oldApkName);
            dialog.dismiss();
//            showInstallDialog("下载完成，是否安装？");
            installApk(context);
            Log.i("DOWNLOAD", "download success");
            Log.i("DOWNLOAD", "totalTime=" + (System.currentTimeMillis() - startTime));
            is.close();
        } catch (Exception ex) {
            dialog.dismiss();
//            up_dialog.dismiss();
            if (context instanceof AppCompatActivity)
            {
                ((Activity)context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context,ex.getMessage()+",请稍后再试试",Toast.LENGTH_SHORT).show();
                    }
                });
            }
            Log.e("DOWNLOAD", "error: " + ex.getMessage(), ex);
        }
    }

    /**
     *  安装APK
     */
    private void installApk(Context context) {
        // Service发的通知中的文件绝对路径
        File file = new File(downLoadPath, newApkName);
        try {
            // 这里有文件流的读写，需要处理一下异常
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //如果SDK版本>=24，即：Build.VERSION.SDK_INT >= 24
                String packageName = context.getApplicationContext().getPackageName();
                String authority = new StringBuilder(packageName).append(".fileprovider").toString();
                Uri uri = FileProvider.getUriForFile(context, authority, file);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
            } else {
                Uri uri = Uri.fromFile(file);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
            }
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 设置context
     */
    public UpdateManager setContext(Context context) {
        this.context = context;
        return this;
    }

    /**
     * apk网络地址
     */
    public UpdateManager setUrl(String url) {
        this.url = url;
        return this;
    }

    /**
     * 新版本文件名
     */
    public UpdateManager setNewFileName(String fileName) {
        this.newApkName = fileName;
        return this;
    }

    /**
     * Fragment管理器
     */
    public UpdateManager setFragmentManager(FragmentManager fm) {
        this.fm = fm;
        return this;
    }

    /**
     * 下载路径
     */
    public UpdateManager setDownloadPath(String downLoadPath) {
        this.downLoadPath = downLoadPath;
        return this;
    }


    /**
     * 是否强制更新
     */
    public UpdateManager setIsforce(String isforce) {
        if (isforce.equals("1"))  this.isforce = true ;
        return this;
    }


    /**
     * 是否强制更新
     */
    public UpdateManager setContent(String  content) {
        this.content = content;
        return this;
    }



}
